package handlers

import (
	"net/http"
	"todo-list/config"
	"todo-list/models"

	"github.com/gin-gonic/gin"
)

// GetAllTodos 获取所有待办事项
func GetAllTodos(c *gin.Context) {
	var todos []models.Todo

	// 从数据库查询所有待办事项
	result := config.DB.Find(&todos)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch todos"})
		return
	}

	c.JSON(http.StatusOK, todos)
}

// AddTodo 添加新的待办事项
func AddTodo(c *gin.Context) {
	var todo models.Todo

	// 绑定请求体到结构体
	if err := c.ShouldBindJSON(&todo); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 保存到数据库
	result := config.DB.Create(&todo)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create todo"})
		return
	}

	c.JSON(http.StatusOK, todo)
}

// UpdateTodo 更新待办事项
func UpdateTodo(c *gin.Context) {
	var todo models.Todo

	// 绑定请求体到结构体
	if err := c.ShouldBindJSON(&todo); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 更新数据库记录
	result := config.DB.Save(&todo)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update todo"})
		return
	}

	c.JSON(http.StatusOK, todo)
}

// DeleteTodo 删除待办事项
func DeleteTodo(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID is required"})
		return
	}

	// 从数据库删除记录
	result := config.DB.Delete(&models.Todo{}, id)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete todo"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"success": true})
}
